using Microsoft.AspNetCore.Mvc;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Applicaticn.Dtos;
using AdminSG3L.Applicaticn.Commands;
using Serilog;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;

namespace AdminSG3L.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class LogController(ILogService logService, IConfiguration configuration, ILogger<LogController> logger) : ControllerBase
{
    private readonly ILogService _logService = logService;
    private readonly IConfiguration _configuration = configuration;
    private readonly ILogger<LogController> _logger = logger;

    /// <summary>
    /// 获取分页日志列表
    /// </summary>
    [HttpGet]
    public async Task<ApiResponse<object>> GetLogs(
        [FromQuery] int pageIndex = 0,
        [FromQuery] int pageSize = 10,
        [FromQuery] string? level = null,
        [FromQuery] string? message = null,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null,
        [FromQuery] string? source = null,
        [FromQuery] string? user = null)
    {
        try
        {
            var search = new LogSearchDto(level, message, startDate, endDate, source, user);
            var result = await _logService.GetPagedLogsAsync(pageIndex, pageSize, search);
            
            if (result.IsSuccess)
            {
                var (logs, totalCount) = result.Data;
                var response = new
                {
                    Logs = logs,
                    TotalCount = totalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                };
                return ApiResponse<object>.Success(response);
            }
            
            return ApiResponse<object>.Fail(result.Message);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.GetLogs异常");
            return ApiResponse<object>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取日志统计
    /// </summary>
    [HttpGet("stats")]
    public async Task<ApiResponse<LogStatsDto>> GetLogStats(
        [FromQuery] string? level = null,
        [FromQuery] string? message = null,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null,
        [FromQuery] string? source = null,
        [FromQuery] string? user = null)
    {
        try
        {
            var search = new LogSearchDto(level, message, startDate, endDate, source, user);
            return await _logService.GetLogStatsAsync(search);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.GetLogStats异常");
            return ApiResponse<LogStatsDto>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 根据ID获取日志详情
    /// </summary>
    [HttpGet("{id}")]
    public async Task<ApiResponse<LogDto?>> GetLogById(Guid id)
    {
        try
        {
            return await _logService.GetLogByIdAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.GetLogById异常，Id={LogId}", id);
            return ApiResponse<LogDto?>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 清除日志
    /// </summary>
    [HttpPost("clear")]
    public async Task<ApiResponse<int>> ClearLogs([FromBody] ClearLogsDto clearLogsDto)
    {
        try
        {
            return await _logService.ClearLogsAsync(clearLogsDto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.ClearLogs异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 导出日志
    /// </summary>
    [HttpGet("export")]
    public async Task<ApiResponse<IEnumerable<LogDto>>> ExportLogs(
        [FromQuery] string? level = null,
        [FromQuery] string? message = null,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null,
        [FromQuery] string? source = null,
        [FromQuery] string? user = null)
    {
        try
        {
            var search = new LogSearchDto(level, message, startDate, endDate, source, user);
            return await _logService.ExportLogsAsync(search);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.ExportLogs异常");
            return ApiResponse<IEnumerable<LogDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 检查日志表结构
    /// </summary>
    [HttpGet("check-tables")]
    public async Task<ApiResponse<object>> CheckTables()
    {
        try
        {
            var connectionString = _configuration.GetConnectionString("Postgres");
            using var connection = new Npgsql.NpgsqlConnection(connectionString);
            await connection.OpenAsync();

            var sql = @"
                SELECT table_name 
                FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name LIKE '%log%'
                ORDER BY table_name";

            using var command = new Npgsql.NpgsqlCommand(sql, connection);
            var tables = new List<string>();
            
            using var reader = await command.ExecuteReaderAsync();
            while (await reader.ReadAsync())
            {
                tables.Add(reader.GetString(0));
            }

            return ApiResponse<object>.Success(new { Tables = tables });
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.CheckTables异常");
            return ApiResponse<object>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 生成测试日志
    /// </summary>
    [HttpPost("test-logs")]
    [AllowAnonymous] // 允许匿名访问以便测试
    public ApiResponse<object> GenerateTestLogs()
    {
        try
        {
            // 生成不同级别的测试日志
            _logger.LogInformation("这是一条信息日志 - 测试ID: {TestId}", Guid.NewGuid());
            _logger.LogWarning("这是一条警告日志 - 测试ID: {TestId}", Guid.NewGuid());
            _logger.LogError("这是一条错误日志 - 测试ID: {TestId}", Guid.NewGuid());
            _logger.LogDebug("这是一条调试日志 - 测试ID: {TestId}", Guid.NewGuid());

            // 使用Serilog也生成一些日志
            Log.Information("Serilog测试信息日志 - {TestId}", Guid.NewGuid());
            Log.Warning("Serilog测试警告日志 - {TestId}", Guid.NewGuid());
            Log.Error("Serilog测试错误日志 - {TestId}", Guid.NewGuid());

            return ApiResponse<object>.Success(new { Message = "测试日志生成成功，已生成7条不同级别的日志" });
        }
        catch (Exception ex)
        {
            Log.Error(ex, "LogController.GenerateTestLogs异常");
            return ApiResponse<object>.Fail($"控制器异常: {ex.Message}");
        }
    }
}
